package cn.earas.ip.netdata;

import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.earas.ip.Data;

public class IPGet_SupperFast implements Runnable {

	private void getIP2(CloseableHttpClient httpClient, String url) {
		final HttpGet get = new HttpGet(url);
		get.setHeader("Host", "www.superfastip.com");
		get.setHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36");
		get.setHeader("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
		get.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
		get.setHeader("Accept-Encoding", "gzip, deflate");
		get.setHeader("Connection", "keep-alive");
		get.setHeader("Upgrade-Insecure-Requests", "1");
		get.setHeader("Pragma", "no-cache");
		get.setHeader("Cache-Control", "no-cache");
		try {
			final HttpEntity entity = httpClient.execute((HttpUriRequest) get).getEntity();
			String result = EntityUtils.toString(entity);
			Document doc = Jsoup.parse(result);
			Elements trs = doc.getElementsByTag("table").get(0).getElementsByTag("tbody").get(0).getElementsByTag("tr");
			for (Element tr : trs) {
				String ip = tr.getElementsByTag("td").get(0).text().trim();
				String port = tr.getElementsByTag("td").get(1).text().trim();
				if (!Data.ips.contains(ip + ":" + port))
					Data.ips.add(ip + ":" + port);
			}
		} catch (ClientProtocolException e2) {
			System.out.println("SupperFastIP\u83b7\u53d6\u5931\u8d25\uff01");
		} catch (Exception e3) {
			System.out.println("SupperFastIP\u83b7\u53d6\u5931\u8d25\uff01");
		}
	}

	@Override
	public void run() {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		for (int i = 1; i <= 10; i++) {
			if(!Data.run) break;
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			this.getIP2(httpClient, "http://www.superfastip.com/welcome/freeIP/" + i);
		}
		try {
			if (httpClient != null)
				httpClient.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
